﻿using System;
using System.Collections.Generic;
using System.Text;
using Framework.Platform.Components.UI.View;
using System.Reflection;
using System.Windows.Forms;

namespace Framework.Platform.Components.UI.Presenter
{
    public abstract class BasePresenter<ViewT> : IDisposable where ViewT : IView
    {
        private bool disposed = false;

        private ViewT _View;

        public ViewT View
        {
            get { return _View; }
            set { _View = value; }
        }

        protected virtual void OnViewSeted()
        {
            this.View.ViewEventRaise += new EventHandler<ViewEventArgs>(View_ViewEventRaise);
        }

        void View_ViewEventRaise(object sender, ViewEventArgs e)
        {
            string methodName = "View_" + e.ViewEventKey;
            MethodInfo eventMethod = this.GetType().GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance);
            if (eventMethod != null)
            {
                eventMethod.Invoke(this, new object[] { sender, e });
            }
            else
            {
                MessageBox.Show(string.Format("没有处理视图事件“{0}”的方法。", e.ViewEventKey));
            }
        }

        public BasePresenter(ViewT view)
        {
            this._View = view;
            this.OnViewSeted();
        }

        #region IDisposable Members

        /// <summary>
        /// See <see cref="System.IDisposable.Dispose"/> for more information.
        /// </summary>
        public void Dispose()
        {
            if (!disposed)
            {
                Dispose(true);
                GC.SuppressFinalize(this);
            }
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (this.View != null)
                {
                    View.Dispose();
                }
            }

            disposed = true;
        }

        #endregion
    }
}
